<template>
  <div class="notification-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Bell /></el-icon>
            <span class="header-title">消息中心</span>
          </div>
          <div class="header-right">
            <el-button 
              type="primary" 
              :disabled="notificationList.length === 0"
              @click="handleMarkAllRead"
            >
              全部标记为已读
            </el-button>
          </div>
        </div>
      </template>
      
      <div v-if="notificationList.length === 0" class="empty-state">
        <el-empty description="暂无消息" />
      </div>
      
      <div v-else class="notification-list">
        <div 
          v-for="item in notificationList" 
          :key="item.id"
          class="notification-item"
          :class="{ 'unread': !item.isRead }"
          @click="handleItemClick(item)"
        >
          <div class="notification-content">
            <div class="notification-header">
              <span class="notification-title">{{ item.title }}</span>
              <span v-if="!item.isRead" class="unread-badge">未读</span>
            </div>
            <div class="notification-body">
              <p class="notification-text">{{ item.content }}</p>
              <span class="notification-time">{{ formatTime(item.createTime) }}</span>
            </div>
          </div>
          <div class="notification-actions">
            <el-button 
              v-if="!item.isRead"
              type="text" 
              size="small"
              @click.stop="handleMarkRead(item.id)"
            >
              标记已读
            </el-button>
            <el-button 
              type="text" 
              size="small"
              @click.stop="handleDelete(item.id)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <div v-if="notificationList.length > 0" class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell } from '@element-plus/icons-vue'

export default {
  name: 'NotificationCenter',
  components: {
    Bell
  },
  setup() {
    const router = useRouter()
    const notificationList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    let refreshTimer = null
    
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else if (diff < 604800000) {
        return Math.floor(diff / 86400000) + '天前'
      } else {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }
    }
    
    const loadNotifications = async () => {
      try {
        const res = await request.get('/notification/list', {
          params: {
            page: currentPage.value,
            size: pageSize.value
          }
        })
        if (res.code === 200 && res.data) {
          notificationList.value = res.data
          total.value = res.data.length // 简化处理，实际应该从后端返回总数
        }
      } catch (error) {
        console.error('加载通知失败', error)
      }
    }
    
    const handleItemClick = (item) => {
      if (!item.isRead) {
        handleMarkRead(item.id)
      }
      
      // 根据通知类型跳转到相应页面
      if (item.type === 'APPROVAL_PENDING') {
        router.push('/approval')
      } else if (item.relatedType === 'OVERTIME') {
        router.push('/attendance/overtime')
      } else if (item.relatedType === 'LEAVE') {
        router.push('/leave')
      }
    }
    
    const handleMarkRead = async (id) => {
      try {
        const res = await request.put(`/notification/read/${id}`)
        if (res.code === 200) {
          const item = notificationList.value.find(n => n.id === id)
          if (item) {
            item.isRead = true
          }
          ElMessage.success('已标记为已读')
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    const handleMarkAllRead = async () => {
      try {
        const res = await request.put('/notification/read-all')
        if (res.code === 200) {
          notificationList.value.forEach(item => {
            item.isRead = true
          })
          ElMessage.success('全部标记为已读')
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    const handleDelete = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await request.delete(`/notification/${id}`)
        if (res.code === 200) {
          notificationList.value = notificationList.value.filter(n => n.id !== id)
          ElMessage.success('删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handlePageChange = () => {
      loadNotifications()
    }
    
    const handleSizeChange = () => {
      currentPage.value = 1
      loadNotifications()
    }
    
    onMounted(() => {
      loadNotifications()
      // 每30秒刷新一次
      refreshTimer = setInterval(() => {
        loadNotifications()
      }, 30000)
    })
    
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer)
      }
    })
    
    return {
      notificationList,
      currentPage,
      pageSize,
      total,
      formatTime,
      handleItemClick,
      handleMarkRead,
      handleMarkAllRead,
      handleDelete,
      handlePageChange,
      handleSizeChange
    }
  }
}
</script>

<style scoped>
.notification-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.empty-state {
  padding: 60px 0;
}

.notification-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
}

.notification-item:hover {
  background: #f5f7fa;
  border-color: #409eff;
}

.notification-item.unread {
  background: #ecf5ff;
  border-color: #409eff;
}

.notification-content {
  flex: 1;
}

.notification-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.notification-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.unread-badge {
  padding: 2px 8px;
  background: #f56c6c;
  color: #fff;
  border-radius: 12px;
  font-size: 12px;
}

.notification-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-text {
  flex: 1;
  margin: 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.notification-time {
  color: #909399;
  font-size: 12px;
  margin-left: 16px;
}

.notification-actions {
  display: flex;
  gap: 8px;
  margin-left: 16px;
}

.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style>

